__dirname = (__dirname || "").toString();

console.log(__dirname);
// 引入 jieba 切词，使语音有停顿
const Jieba = require("node-jieba");
// 引入 fileSystem 文件操作模块
const fs = require("fs");
// 引入 path 路径操作模块
const path = require("path");
// 给字符串加上.toPinYin函数
require("./util/pinYinUtil");

const WAV_PATH = path.join(__dirname, "../Mix/");
const IS_NEED_PIN_HUA = true; // 是否平滑，去掉静音，与连接处平滑的地方，会好性能 false 6s true 8s
const NUMBER_ARR = ["ling2", "yi1", "er4", "san1", "si4", "wu3", "liu4", "qi1", "ba1", "jiu3"]; // 是否平滑，去掉静音，与连接处平滑的地方，会好性能 false 6s true 8s


var analyzer = Jieba({
    debug: false
});

function textToSpeech(arg, cb) {
    analyzer.cut('任意字段', {
        mode: Jieba.mode.TERM,
        HMM: true
    }, function (err, result) {
        if (!err) {
            console.log(result.join(" ").toPinYin(false, false));
        }
        // var pinYinStr = "sui1,ran2,1,zhong4,yao4,1,ren4,wu4,1,mian4,qian2,1,gu4,yi4,1,fang4,shui3";
        // var pinYinStr = "zao3,shang4,2,hao3";
        // var pinYinStr = `zhu3,ren2,de0,1,ming4,ling4,2,shi4,1,jue2,dui4,de0`;
        var numberStr = arg.numberStr || "";
        var pinYinStr = arg.pinYinStr || "";
        numberStr.split("").forEach(function (element) {
            pinYinStr += "," + NUMBER_ARR[Number(element)];
        }, this);
        pinYinStr = pinYinStr.substr(1);
        // pinYinStr += ",ai1,ke4,si1";
        var pinYinArr = pinYinStr.split(",");
        var wavData = fs.readFileSync(path.join(__dirname, "./src/wav/silence.wav"));//new Buffer(44100*4*10);
        var wavDataIndex = 64;
        for (var i = 0; i < pinYinArr.length; i++) {
            if (" 012345".indexOf(pinYinArr[i]) > -1) {
                var waitTime = 0;
                if (pinYinArr[i] == " ") waitTime = 5;
                else waitTime = Number(pinYinArr[i]);
                let wavDataPart = new Buffer((44100 * 4 / 20) * waitTime);
                wavDataPart.copy(wavData, wavDataIndex, 64, wavDataPart.length);
                wavDataIndex += wavDataPart.length - 64;
                console.log(wavDataIndex);
            } else {
                let wavPath = path.join(WAV_PATH, `${pinYinArr[i]}.wav`);
                console.log(fs.existsSync(wavPath));
                if (fs.existsSync(wavPath)) {
                    let wavDataPart = fs.readFileSync(wavPath);
                    var wavDataLen = wavDataPart.length;
                    var halfWavDataLen = wavDataLen / 2;
                    // 平滑处理 开头_/ 结尾/^
                    var j1 = 0;
                    var j2 = 0;
                    if (IS_NEED_PIN_HUA) {
                        for (; j1 < halfWavDataLen; j1 += 2) {
                            let score = Number(wavDataPart[112 + 2 * j1]) + Number(wavDataPart[112 + 2 * j1] * 256);
                            if (score < 1000) {
                                let nextScore = Number(wavDataPart[72 + 2 * j1 + 8]) + Number(wavDataPart[73 + 2 * j1 + 8] * 256);
                                if (nextScore > score + 10 && nextScore < 32768) {
                                    console.log("j1", j1, score, nextScore);
                                    break;
                                }
                            }
                        }
                        for (; j2 < halfWavDataLen; j2 += 2) {
                            let score = Number(wavDataPart[wavDataLen - 36 - 2 * j2 - 2]) + Number(wavDataPart[wavDataLen - 36 - 2 * j2 - 1]) * 256;
                            if (i == 0) {
                                console.log("score", score, wavDataPart[wavDataLen - 2 * j2 - 2], Number(wavDataPart[wavDataLen - 2 * j2 - 2]), Number(wavDataPart[wavDataLen - 2 * j2 - 1]));
                            }
                            if (score > 64536) {
                                let lastScore = Number(wavDataPart[wavDataLen - 2 * j2 - 2 - 8]) + Number(wavDataPart[wavDataLen - 2 * j2 - 1 - 8]) * 256;
                                if (lastScore < score - 10 && lastScore > 32768) {
                                    console.log("j2", j2, score, lastScore);
                                    break;
                                }
                            }
                        }
                    }
                    // 把新读取到的wav文件 拷贝到混合的wav文件中， 1混合wav 2从混合wav的哪里开始 3从新wav的哪里开始 4到wav的哪里之前结束
                    wavDataPart.copy(wavData, wavDataIndex, 112 + j1, wavDataLen - 36 - j2);
                    wavDataIndex += wavDataLen - 144 - j2 - j1;
                    console.log(wavDataIndex);
                } else {
                    var waitTime = 10;
                    let wavDataPart = new Buffer((44100 * 4 / 20) * waitTime);
                    wavDataPart.copy(wavData, wavDataIndex, 64, wavDataPart.length);
                    wavDataIndex += wavDataPart.length - 64;
                    console.log(wavDataIndex);
                }
            }
        }
        fs.writeFileSync(path.join(__dirname, `./out/wav/${numberStr || pinYinStr}.wav`), wavData.slice(0, wavDataIndex+1));
        cb(path.join(__dirname, `./out/wav/${numberStr || pinYinStr}.wav`));
    });
}

textToSpeech({
    numberStr: "",
    // pinYinStr: ",zhi1,ma0,kai1,meng2"
    pinYinStr: ",ji2,bang4,shi4,shen2,me0,yi4,si0"
}, (a)=>{console.log(a)})

module.exports.textToSpeech = textToSpeech;

function setWavHeader() {

}